<template>
  <div class="execution-logs-page">
    <h1>执行日志</h1>

    <!-- 错误信息显示 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert
        :title="errorMessage"
        type="error"
        show-icon
        closable
        @close="errorMessage = ''"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="executionLogs.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无执行日志" />
      <el-button type="primary" @click="$router.push('/scripts')">
        去执行脚本
      </el-button>
    </div>

    <!-- 执行日志表格 -->
    <div v-else>
      <el-table 
        :data="executionLogs" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
        @row-click="viewLogDetails"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="脚本名称">
          <template #default="scope">
            {{ scope.row.script?.name || '未知脚本' }}
          </template>
        </el-table-column>
        <el-table-column label="语言" width="100">
          <template #default="scope">
            <el-tag size="small" :type="getLanguageType(scope.row.script?.language)">
              {{ getLanguageName(scope.row.script?.language) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status || 'unknown' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executed_at" label="执行时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.executed_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="completed_at" label="完成时间" width="180">
          <template #default="scope">
            {{ scope.row.completed_at ? formatDate(scope.row.completed_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewLogDetails(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="showLogDialog"
      :title="`执行日志详情 - ${selectedLog?.script?.name || '未知脚本'}`"
      width="90%"
      style="max-width: 1200px;"
      class="log-detail-dialog"
      @opened="onLogDialogOpened"
    >
      <div v-if="selectedLog" class="log-detail">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 执行结果标签页 -->
          <el-tab-pane label="执行结果" name="result">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="脚本名称">
                {{ selectedLog.script?.name || '未知脚本' }}
              </el-descriptions-item>
              <el-descriptions-item label="语言">
                <el-tag :type="getLanguageType(selectedLog.script?.language)">
                  {{ getLanguageName(selectedLog.script?.language) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(selectedLog.status)">
                  {{ selectedLog.status || 'unknown' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="执行时间">
                {{ formatDate(selectedLog.executed_at) }}
              </el-descriptions-item>
              <el-descriptions-item label="完成时间">
                {{ selectedLog.completed_at ? formatDate(selectedLog.completed_at) : '-' }}
              </el-descriptions-item>
            </el-descriptions>

            <el-divider>执行输出</el-divider>
            
            <div v-if="selectedLog.output" class="log-output">
              <pre>{{ selectedLog.output }}</pre>
            </div>
            <div v-else class="no-output">
              <el-empty description="暂无输出" :image-size="80" />
            </div>

            <el-divider v-if="selectedLog.error_message">错误信息</el-divider>
            
            <div v-if="selectedLog.error_message" class="error-output">
              <pre>{{ selectedLog.error_message }}</pre>
            </div>
          </el-tab-pane>

          <!-- 脚本内容标签页 -->
          <el-tab-pane label="脚本内容" name="content">
            <div v-if="selectedLog.script" class="script-content">
              <AceEditor
                :model-value="selectedLog.script.content"
                :language="selectedLog.script.language"
                :theme="'monokai'"
                :read-only="true"
                :show-gutter="true"
                :height="'500px'"
                :auto-width="true"
                @init="onScriptEditorInit"
              />
            </div>
            <div v-else class="no-script">
              <el-empty description="无法获取脚本内容" :image-size="80" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '../services/api'
import AceEditor from '../components/AceEditor.vue'
import { ensureArray, cleanExecutionLogData } from '../utils/validation'

export default {
  name: 'ExecutionLogs',
  components: {
    AceEditor
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const executionLogs = ref([])
    const showLogDialog = ref(false)
    const selectedLog = ref(null)
    const loading = ref(false)
    const activeTab = ref('result')
    const scriptEditorInstance = ref(null)
    const errorMessage = ref('')
    const fetchExecutionLogs = async () => {
  loading.value = true
  errorMessage.value = ''
  try {
    console.log('开始获取执行日志...')
    const response = await api.get('/execution-logs/')
    console.log('执行日志响应:', response.data)
    // 使用验证工具确保数据安全
    executionLogs.value = ensureArray(response.data).map(cleanExecutionLogData)
  } catch (error) {
    console.error('获取执行日志失败:', error)
    const message = error.response?.data?.detail || error.message || '获取执行日志失败'
    errorMessage.value = message
    ElMessage.error(message)
    executionLogs.value = []
  } finally {
    loading.value = false
  }
}

    const viewLogDetails = async (log) => {
      try {
        console.log('查看日志详情:', log.id)
        const response = await api.get(`/execution-logs/${log.id}`)
        selectedLog.value = response.data
        activeTab.value = 'result'
        showLogDialog.value = true
      } catch (error) {
        console.error('获取日志详情失败:', error)
        const message = error.response?.data?.detail || error.message || '获取日志详情失败'
        ElMessage.error(message)
      }
    }

    const onScriptEditorInit = (editor) => {
      scriptEditorInstance.value = editor
      console.log('脚本编辑器初始化完成')
    }

    const onLogDialogOpened = () => {
      // 对话框打开后调整编辑器大小
      if (scriptEditorInstance.value) {
        scriptEditorInstance.value.resize()
        console.log('脚本编辑器大小已调整')
      }
    }

    const getStatusType = (status) => {
      const types = {
        'success': 'success',
        'running': 'primary',
        'pending': 'info',
        'failed': 'danger'
      }
      return types[status] || 'info'
    }

    const getLanguageType = (language) => {
      const types = {
        'python': 'success',
        'shell': 'warning',
        'javascript': 'primary'
      }
      return types[language] || 'info'
    }

    const getLanguageName = (language) => {
      const names = {
        'python': 'Python',
        'shell': 'Shell',
        'javascript': 'JavaScript'
      }
      return names[language] || language || '未知'
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      try {
        return new Date(dateString).toLocaleString('zh-CN')
      } catch (error) {
        console.error('日期格式化错误:', error)
        return dateString
      }
    }

    // 监听路由变化
    watch(() => route.query, (newQuery) => {
      if (newQuery.log_id && executionLogs.value.length > 0) {
        const log = executionLogs.value.find(l => l.id == newQuery.log_id)
        if (log) {
          viewLogDetails(log)
        }
      }
    })

    onMounted(() => {
      console.log('执行日志页面已加载')
      fetchExecutionLogs()
    })

    return {
      executionLogs,
      showLogDialog,
      selectedLog,
      loading,
      activeTab,
      errorMessage,
      viewLogDetails,
      onScriptEditorInit,
      onLogDialogOpened,
      getStatusType,
      getLanguageType,
      getLanguageName,
      formatDate
    }
  }
}
</script>

<style scoped>
.execution-logs-page {
  padding: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state .el-button {
  margin-top: 20px;
}

.log-detail {
  padding: 0;
}

.log-output, .error-output {
  background: #1e1e1e;
  padding: 15px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  color: #d4d4d4;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
}

.log-output pre, .error-output pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.no-output, .no-script {
  text-align: center;
  color: #999;
  padding: 40px;
}

.script-content {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
}

.log-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.log-detail-dialog :deep(.el-tabs__content) {
  padding: 20px;
}

/* 表格行可点击 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
